1. 题目

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/add-two-numbers 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题思路

注意是数字在链表中逆序存储。

链表的基操。注意此题中不含表头结点

3. 代码

3.1. 循环写法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *head=nullptr,*tmp=NULL;
        int num,carry=0,n1,n2;
        int i=0;
        while(1){
            if(l1==nullptr&&l2==nullptr&&!carry) {
                tmp->next=nullptr;
                break;
            }
            cout<<"I: "<<++i<<endl;
            n1=(l1==nullptr)?0:l1->val;
            n2=(l2==nullptr)?0:l2->val;
            if(l1) l1=l1->next;
            if(l2) l2=l2->next;
            num=n1+n2+carry;
            carry=num/10;

            if(!head){
                head=new ListNode(num%10);
                tmp=head;
            }else{
                tmp->next=new ListNode(num%10);
                tmp=tmp->next;
            }
        }
        return head;

    }

    void print(ListNode* head){
        while(head!=NULL){
            cout<<(head->val);
            head=head->next;
        }
    }
};

3.2. 递归写法

看题解看到一种递归写法。但和上面一种解法相比而言,运行时间并没有改善。但代码很美。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        return dfs(l1, l2, 0);
    }

    ListNode* dfs(ListNode* l, ListNode* r, int i) {
        if (!l && !r && !i) return nullptr;
        int sum = (l ? l->val : 0) + (r ? r->val : 0) + i;
        ListNode* node = new ListNode(sum % 10);
        node->next = dfs(l ? l->next : nullptr, r ? r->next : nullptr, sum / 10);
        return node;
    } 
};

results matching ""

    No results matching ""